import { lazy } from "react";
import {
  Navigate,
  createBrowserRouter,
  RouterProvider,
  type RouteObject,
} from "react-router-dom";
import Login from "@/pages/login";
import type { AppRouteObject } from "types/router";
import { ErrorBoundary } from "react-error-boundary";
import ProtectedRoute from "./components/Protected-route";
import Layout from "@/Layout/index";
import { usePermissionRoutes } from "./hooks/use-permissions";

const PageError = lazy(() => import("@/pages/404/NotFound")); // 404页面

const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env;

// 定义公共路由
const PUBLIC_ROUTES: AppRouteObject = {
  path: "/login",
  element: (
    <ErrorBoundary FallbackComponent={PageError}>
      <Login />
    </ErrorBoundary>
  ),
  meta: {
    key: "login",
    label: "登录",
    hideMenu: true,
  },
};

// 定义404路由
const NOT_FOUND_ROUTE: AppRouteObject = {
  path: "/404",
  element: (
    <ErrorBoundary FallbackComponent={PageError}>
      <PageError />
    </ErrorBoundary>
  ),
  meta: {
    key: "404",
    label: "404",
    hideMenu: true,
  },
};

// 定义未匹配路由（404页面）
const NO_MATCHED_ROUTE: AppRouteObject = {
  path: "*",
  element: <Navigate to="/404" replace />,
};

export default function Router() {
  const permissions = usePermissionRoutes() as RouteObject[];

  const PROTECTED_ROUTE: AppRouteObject = {
    path: "/",
    element: (
      <ProtectedRoute>
        <Layout />
      </ProtectedRoute>
    ),
    children: [
      { index: true, element: <Navigate to={HOMEPAGE} replace /> },
      ...permissions,
    ],
  };

  // 定义所有路由
  const routes = [
    PROTECTED_ROUTE,
    PUBLIC_ROUTES,
    NOT_FOUND_ROUTE,
    NO_MATCHED_ROUTE,
  ] as RouteObject[];
  const router = createBrowserRouter(routes);

  return <RouterProvider router={router} />;
}
